package cn.starfire.sttool.tools;


import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.text.Font;
import javafx.stage.FileChooser;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Set;

/**
 * @description:
 * @author: tanpengji
 * @time: 2025/8/27 09:49
 */
public class JsonToExcelTool implements ToolModule {

    @Override
    public String getName() {
        return "JSON → Excel";
    }

    @Override
    public VBox getContent() {
        // JSON 输入区域
        TextArea jsonInput = new TextArea();
        jsonInput.setPromptText("在这里粘贴 JSON 数组...");
        jsonInput.setFont(Font.font("Consolas", 14));
        jsonInput.setWrapText(true);
        jsonInput.setPrefHeight(200);

        // 导出按钮
        Button exportBtn = new Button("导出 Excel");
        exportBtn.setStyle("-fx-background-color: #2196F3; -fx-text-fill: white; -fx-font-weight: bold;");
        exportBtn.setPrefWidth(120);
        exportBtn.setFont(Font.font(14));

        // 状态信息
        Label statusLabel = new Label();
        statusLabel.setFont(Font.font(13));
        statusLabel.setWrapText(true);

        exportBtn.setOnAction(e -> {
            try {
                String json = jsonInput.getText().trim();
                JSONArray array = JSONArray.parseArray(json);
                if (array == null || array.isEmpty()) {
                    statusLabel.setText("请输入合法的 JSON 数组！");
                    return;
                }

                FileChooser fileChooser = new FileChooser();
                fileChooser.setTitle("保存 Excel 文件");
                fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Excel 文件", "*.xlsx"));
                File file = fileChooser.showSaveDialog(null);
                if (file == null) return;

                Workbook workbook = new XSSFWorkbook();
                Sheet sheet = workbook.createSheet("Data");

                // 写入表头并加粗
                JSONObject first = array.getJSONObject(0);
                Set<String> keys = first.keySet();
                Row headerRow = sheet.createRow(0);

                CellStyle headerStyle = workbook.createCellStyle();
                org.apache.poi.ss.usermodel.Font headerFont = workbook.createFont(); // 用全路径
                headerFont.setBold(true);
                headerStyle.setFont(headerFont);

                int col = 0;
                for (String key : keys) {
                    Cell cell = headerRow.createCell(col++);
                    cell.setCellValue(key);
                    cell.setCellStyle(headerStyle);
                }

                // 写入数据
                for (int i = 0; i < array.size(); i++) {
                    JSONObject obj = array.getJSONObject(i);
                    Row row = sheet.createRow(i + 1);
                    int c = 0;
                    for (String key : keys) {
                        Object value = obj.getOrDefault(key, "");
                        row.createCell(c++).setCellValue(String.valueOf(value));
                    }
                }

                // 保存文件
                FileOutputStream fos = new FileOutputStream(file);
                workbook.write(fos);
                workbook.close();
                fos.close();

                statusLabel.setText("导出成功：" + file.getAbsolutePath());
            } catch (Exception ex) {
                statusLabel.setText("导出失败：" + ex.getMessage());
                ex.printStackTrace();
            }
        });

        VBox root = new VBox(15,
                new Label("JSON 输入："),
                jsonInput,
                exportBtn,
                statusLabel
        );
        root.setPadding(new Insets(20));
        root.setStyle("-fx-background-color: #f9f9f9; -fx-border-color: #ccc; -fx-border-radius: 5px; -fx-background-radius: 5px;");

        return root;
    }

}
